<template>
  <n-card :bordered="false">
    <BasicForm @register="register" @submit="handleSubmit">
    </BasicForm>
  </n-card>

  <n-card :bordered="false" class="mt-3" title="用户列表">
    <n-button type="primary" @click="getAddUser">
      <template #icon>
        <n-icon>
          <PlusOutlined />
        </n-icon>
      </template>
      新增用户
    </n-button>

    <BasicTable :columns="columns" :request="loadDataTable" :row-key="(row) => row.userId" ref="actionRef"
      :action-column="actionColumn" :scroll-x="1090" :striped="true" />
  </n-card>

  <n-modal v-model:show="showModal" style="width:60%" :show-icon="false" preset="dialog"
    :title="isEdit ? '编辑用户' : '新增用户'">
    <n-form :model="formParams" :rules="rules" ref="formRef" label-placement="left" :label-width="80" class="py-4">
      <n-grid :cols="2" :x-gap="12">
        <n-grid-item>
          <n-form-item label="昵称" path="nickname">
            <n-input placeholder="请输入用户昵称" v-model:value="formParams.nickname" />
          </n-form-item>
        </n-grid-item>
        <n-grid-item>
          <n-form-item label="性别" path="gender">
            <n-select placeholder="请选择性别" v-model:value="formParams.gender" :options="genderOptions" />
          </n-form-item>
        </n-grid-item>
        <n-grid-item>
          <n-form-item label="手机号" path="phone">
            <n-input placeholder="请输入手机号" v-model:value="formParams.phone" maxlength="11" :disabled="isEdit" />
          </n-form-item>
        </n-grid-item>
        <n-grid-item>
          <n-form-item label="密码" path="password">
            <n-input type="password" :placeholder="isEdit ? '密码不可修改' : '请输入密码'" maxlength="20"
              v-model:value="formParams.password" :disabled="isEdit" />
          </n-form-item>
        </n-grid-item>
      </n-grid>
    </n-form>

    <template #action>
      <n-space>
        <n-button @click="() => (showModal = false)">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
      </n-space>
    </template>
  </n-modal>
</template>

<script lang="ts" setup>
import { h, reactive, ref } from 'vue';
import { BasicTable, TableAction } from '@/components/Table';
import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
import { getUserDatas, addUser, updateUser } from '@/api/system/user';
import type { UserItem, UpdateUserParams } from '@/api/system/user';
import { columns } from './columns';
import { PlusOutlined } from '@vicons/antd';
import { useMessage, useDialog } from 'naive-ui'


const message = useMessage()
const dialog = useDialog()

const schemas: FormSchema[] = [
  {
    field: 'nickname',
    component: 'NInput',
    label: '昵称',
    componentProps: {
      placeholder: '请输入用户昵称',
    },
  },
  {
    field: 'phone',
    component: 'NInput',
    label: '手机号',
    componentProps: {
      placeholder: '请输入手机号',
    },
  },
  {
    field: 'gender',
    component: 'NSelect',
    label: '性别',
    componentProps: {
      placeholder: '请选择性别',
      options: [
        { label: '男', value: true },
        { label: '女', value: false },
      ],
    },
  },
  {
    field: 'status',
    component: 'NSelect',
    label: '状态',
    componentProps: {
      placeholder: '请选择状态',
      options: [
        { label: '正常', value: 1 },
        { label: '封禁', value: 2 },
        { label: '已注销', value: 3 },
      ],
    },
  },
];
const [register, { getFieldsValue, resetFields }] = useForm({
  gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
  labelWidth: 80,
  schemas,
});

const genderOptions = ref([
  { label: '男', value: true },
  { label: '女', value: false },
])

const actionRef = ref();
const checkedRowKeys = ref<(string | number)[]>([]);

const loadDataTable = async (params) => {
  return await getUserDatas({ ...getFieldsValue(), ...params });
};

function reloadTable() {
  actionRef.value.reload();
}

function handleSubmit() {
  reloadTable();
}

const actionColumn = reactive({
  width: 220,
  title: '操作',
  key: 'action',
  align: 'center',
  fixed: 'right',
  render(record: UserItem) {
    return h(TableAction as any, {
      style: 'text',
      actions: [
        {
          label: '编辑',
          color: '#2D8CF0',
          onClick: handleEdit.bind(null, record),
        }
      ],
      dropDownActions: [
        {
          label: '封禁',
          key: 'ban',
          ifShow: () => record.status === 1,
        },
        {
          label: '解封',
          key: 'unban',
          ifShow: () => record.status === 2,
        },
        {
          label: '注销',
          key: 'logout',
          ifShow: () => record.status === 1 || record.status === 2,
        },
      ],
      select: (key) => {
        if (key === 'ban') {
          // 🌟 封禁操作前添加确认
          dialog.warning({
            title: '警告',
            content: `你确定要封禁用户【${record.nickname}】吗？`,
            positiveText: '确定',
            negativeText: '取消',
            draggable: true,
            onPositiveClick: () => {
              // 用户点击“确定”后，才执行封禁逻辑
              updateUserStatus(record, 2);
            },
            onNegativeClick: () => {
              // 用户点击“取消”，什么也不做
              // message.info('已取消封禁');
            }
          });
        } else if (key === 'unban') {
          dialog.warning({
            title: '警告',
            content: `你确定要解封用户【${record.nickname}】吗？`,
            positiveText: '确定',
            negativeText: '取消',
            draggable: true,
            onPositiveClick: () => {
              // 用户点击“确定”后，才执行解封逻辑
              updateUserStatus(record, 1);
            },
            onNegativeClick: () => {
              // 用户点击“取消”，什么也不做
              // message.info('已取消封禁');
            }
          });
        } else if (key === 'logout') {
          // 🌟 注销操作前添加确认
          dialog.warning({
            title: '警告',
            content: `你确定要注销用户【${record.nickname}】吗？此操作不可逆！`,
            positiveText: '确定',
            negativeText: '取消',
            draggable: true,
            onPositiveClick: () => {
              // 用户点击“确定”后，才执行注销逻辑
              updateUserStatus(record, 3);
            },
            onNegativeClick: () => {
              // 用户点击“取消”，什么也不做
              // message.info('已取消注销');
            }
          });
        }
      },
    });
  },
});

const showModal = ref(false);
const isEdit = ref(false);
const formRef: any = ref(null);
const formBtnLoading = ref(false);
const formParams = reactive({
  userId: 0,
  nickname: '',
  phone: '',
  gender: undefined,
  password: '',
  status: undefined,
  avatar: ''
});

const rules = {
  nickname: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入用户昵称',
  },
  phone: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入手机号',
  },
  gender: {
    validator(rule: any, value: any) {
      if (value === undefined || value === null) {
        return new Error('请选择性别');
      }
      return true;
    },
    trigger: ['change'],
  },
  password: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入密码',
  },
};

function getAddUser() {
  formParams.userId = 0;
  formParams.nickname = '';
  formParams.phone = '';
  formParams.gender = undefined;
  formParams.password = '';
  isEdit.value = false;
  showModal.value = true;
}

function handleEdit(record: UserItem) {
  console.log('编辑用户:', record);
  formParams.userId = record.userId;
  formParams.nickname = record.nickname;
  formParams.phone = record.phone;
  formParams.gender = record.gender;
  formParams.password = '******';
  formParams.status = record.status;
  isEdit.value = true;
  showModal.value = true;
}

async function confirmForm() {
  formRef.value.validate(async (errors) => {
    if (!errors) {
      formBtnLoading.value = true;
      try {
        if (isEdit.value) {
          const updateData: UpdateUserParams = {
            userId: formParams.userId,
            phone: formParams.phone,
            nickname: formParams.nickname,
            gender: formParams.gender,
            avatar: formParams.avatar,
            status: formParams.status,
          };
          await updateUser(updateData); // 🌟 这里也应该加 await
          message.success('编辑成功');
        } else {
          await addUser(formParams);
          message.success('新增成功');
        }
        showModal.value = false;
        reloadTable();
      } catch (error) {
        console.error('操作失败:', error);
        message.error('操作失败，请稍后重试');
      } finally {
        formBtnLoading.value = false;
      }
    }
  });
}

async function updateUserStatus(user: UserItem, targetStatus: number) {
  const actionTextMap = { 1: '解封', 2: '封禁', 3: '注销' };
  const actionText = actionTextMap[targetStatus] || '更新状态';

  try {
    const updateData: UpdateUserParams = {
      userId: user.userId,
      phone: user.phone,
      nickname: user.nickname,
      gender: user.gender,
      avatar: user.avatar,
      status: targetStatus,
    };

    await updateUser(updateData);
    message.success(`成功${actionText} 用户 ${user.nickname}`);
    reloadTable();
    checkedRowKeys.value = [];
  } catch (error) {
    console.error(`${actionText}失败:`, error);
    message.error(`${actionText}失败，请稍后重试`);
  }
}
</script>